# coding: utf8
import requests
from wxpy import *
import time
import json
import webbrowser

def gbk_raw_input(val):
	"""Windows命令行输出gbk文本"""
	return raw_input(to_gbk('>>>'+val))

def to_gbk(val):
	"""返回gbk"""
	if isinstance(val, unicode):
		val = val.encode('utf8')
	return unicode(val, 'utf-8').encode('gbk')

def get_image(url):
	
	if (url.find('.jpg')==-1 and url.find('.png')==-1 ) or \
		(url.find('https://')==-1 and url.find('http://')==-1):
		return
	r = requests.get(url, timeout=2)
	fn = url[-9:]
	with open(fn, 'wb') as f:
		f.write(r.content)
	return fn

def chat_for_friend(friends):
	FIND_ = gbk_raw_input('输入好友昵称开始聊天:')
	friend = friends.search(unicode(FIND_, 'gbk'))[0]
	while True:
		raw_input()
		MSG_ = gbk_raw_input('我的信息:')
		if MSG_ in ['r', 'R']:
			break
		friend.send(unicode(MSG_, 'gbk'))

def chat_for_group(groups):
	FIND_ = gbk_raw_input('输入群昵称开始聊天:')
	group = groups.search(unicode(FIND_, 'gbk'))[0]

	while True:
		raw_input()
		MSG_ = gbk_raw_input('我的信息:')
		if MSG_ in ['r', 'R']:
			break
		if '.jpg' in MSG_ or '.png' in MSG_:
			group.send_image(MSG_)
		else:
			group.send(unicode(MSG_, 'gbk'))

def qr_callback(uuid=None, status=None, qrcode=None):
	# path = 'C:/Users/you/Desktop/workspace.git/Document/Python/tornado_pro/demo1/static/img/qr.png'
	path = 'C:/Users/you/Desktop/workspace.git/Document/Python/tornado_pro/demo1/static/img/uuid.txt'
	# with open(path, 'wb') as f:
	# 	f.write(qrcode)
	with open(path, 'wb') as f:
		f.write(uuid)

def login_callback():
	path = 'C:/Users/you/Desktop/workspace.git/Document/Python/tornado_pro/demo1/static/img/login_status.txt'
	with open(path, 'wb') as f:
		f.write('OK')

def run():
	bot = Bot(cache_path=True, qr_callback=qr_callback, login_callback=login_callback)
	groups = bot.groups() # 群列表
	friends = bot.friends() # 好友列表
	bot.enable_puid() # 开启puid 可判断群唯一, 微信朋友的唯一
	@bot.register([Group, Friend], TEXT)
	def print_group_msg(msg):
		print(msg)
	
	# while True:
	# 	FIND_ = gbk_raw_input('F(和朋友聊), G(和群聊):')
	# 	if FIND_ in ['f', 'F']:
	# 		chat_for_friend(friends)
	# 	elif FIND_ in ['g', 'G']:
	# 		chat_for_group(groups)
			
	return bot
	# embed()
if __name__ == '__main__':
	# groups = run()
	pass
		

